/**
 *
 */

package com.person.modules.person.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.person.common.utils.Constant;
import com.person.common.utils.DateUtils;
import com.person.common.utils.PageUtils;
import com.person.common.utils.Query;
import com.person.modules.person.dao.UserDocDao;
import com.person.modules.person.entity.*;
import com.person.modules.person.service.PunishmentService;
import com.person.modules.person.service.UserDocEvaluateService;
import com.person.modules.person.service.UserDocService;
import com.person.modules.person.service.WorkRecordService;
import com.person.modules.sys.dao.SysUserDao;
import com.person.modules.sys.entity.SysCompanyUserEntity;
import com.person.modules.sys.entity.SysDeptEntity;
import com.person.modules.sys.entity.SysUserEntity;
import com.person.modules.sys.entity.SysUserRoleEntity;
import com.person.modules.sys.service.SysCompanyUserService;
import com.person.modules.sys.service.SysDeptService;
import com.person.modules.sys.service.SysUserRoleService;
import com.person.modules.sys.service.SysUserService;
import com.person.modules.sys.shiro.ShiroUtils;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.xml.crypto.Data;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;


@Service("userDocService")
public class UserDocServiceImpl extends ServiceImpl<UserDocDao, UserDocEntity> implements UserDocService {
    @Autowired
    SysUserService userService;
    @Autowired
    SysDeptService sysDeptService;
    @Autowired
    SysUserRoleService sysUserRoleService;
    @Autowired
    UserDocDao userDocDao;
    @Autowired
    SysUserDao sysUserDao;
    @Autowired
    SysCompanyUserService sysCompanyUserService;
    @Autowired
    SysUserService sysUserService;
    @Autowired
    PunishmentService punishmentService;
    @Autowired
    UserDocEvaluateService userDocEvaluateService;
    @Autowired
    WorkRecordService workRecordService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        Object id = params.get("userId");
        Long userId = null;
        if (!ObjectUtils.isEmpty(id)) {
            userId = (Long) id;
        }
        Object dId = params.get("deptId");
        Long deptId = null;
        if (!ObjectUtils.isEmpty(dId)) {
            deptId = Long.parseLong(dId.toString());
        }

        IPage<UserDocEntity> page = this.page(
                new Query<UserDocEntity>().getPage(params),
                new QueryWrapper<UserDocEntity>()
                        .eq(null != userId, "user_id", userId)
                        .eq(null != deptId, "dept_id", deptId)
                        .apply(params.get(Constant.SQL_FILTER) != null, (String) params.get(Constant.SQL_FILTER))

        );
        List<UserDocEntity> records = page.getRecords();

        List<UserDocEntity> list = new ArrayList<UserDocEntity>();
        for (UserDocEntity r : records) {
            String birthYear = r.getIdentityCard().substring(0, 4);
            String year = DateUtils.format(new Date(), "YYYY");
            int age = Integer.valueOf(year) - Integer.valueOf(birthYear);
            r.setAge(age);
            r.setName(userService.getById(r.getUserId()).getName());
            SysDeptEntity sysDeptEntity = sysDeptService.getById(r.getDeptId());
            r.setDeptName(sysDeptEntity.getName());
            list.add(r);
        }
        page.setRecords(list);
        return new PageUtils(page);
    }

    @Override
    public void deleteBatch(Long[] ids) {
        this.removeByIds(Arrays.asList(ids));

    }

    @Override
    public void update(UserDocEntity record) {
        this.updateById(record);
    }

    public List<UserDocEntity> getDocList(Long companyId) {
        return userDocDao.getDocList(companyId);
    }


    /**
     * 员工离职   需要修改status和增加离职时间
     *
     * @param ids
     */
    @Override
    public void leaveCompany(Long ids) {
        Date date = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String leaveDate = dateFormat.format(date);
        System.out.println(ids);
        userDocDao.updateLeaveTime(ids, leaveDate);
        userDocDao.updateStatus(ids);
    }
    @Override
    public void add(UserDocEntity userDocEntity) {
        userDocDao.add(userDocEntity);
        Long userId = userDocEntity.getUserId();
        SysCompanyUserEntity sysCompanyUserEntity = new SysCompanyUserEntity();
        sysCompanyUserEntity.setCompany_id(userDocEntity.getCompanyId());
        sysCompanyUserEntity.setUser_id(userId);
        sysCompanyUserEntity.setStatus(1);
        sysCompanyUserService.save(sysCompanyUserEntity);
        if (userDocEntity.getUserType() == 3 ||userDocEntity.getUserType()==4) {
            SysUserEntity sysUserEntity = new SysUserEntity();
            //获取盐
            String salt = RandomStringUtils.randomAlphanumeric(20);
            sysUserEntity.setSalt(salt);
            sysUserEntity.setPassword(ShiroUtils.sha256(userDocEntity.getPassword(), salt));
            sysUserEntity.setRoleId(Long.valueOf(userDocEntity.getUserType()));
            sysUserEntity.setCompanyId(userDocEntity.getCompanyId());
            try {
                SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Date createTime = formatter.parse(userDocEntity.getCreateTime());
                sysUserEntity.setCreateTime(createTime);
            } catch (ParseException e) {
                e.printStackTrace();

            }
            sysUserEntity.setStatus(1);
            sysUserEntity.setDeptId(userDocEntity.getDeptId());
            sysUserEntity.setUsername(userDocEntity.getUsername());
            sysUserEntity.setRoleId(Long.valueOf(userDocEntity.getUserType()));
            sysUserDao.add(sysUserEntity);
            Long id=sysUserEntity.getUserId();
            SysUserRoleEntity sysUserRoleEntity=new SysUserRoleEntity();
            sysUserRoleEntity.setUserId(id);
            sysUserRoleEntity.setRoleId(Long.valueOf(userDocEntity.getUserType()));
            sysUserRoleService.save(sysUserRoleEntity);
        }
    }

    @Override
    public  List<UserDocEntity> queryListByCompanyId(Long companyId) {
      List<UserDocEntity> list = userDocDao.queryListByCompanyId(companyId);
      return list;
    }

    @Override
    public List<UserDocEntity> queryUserDocBackground(String name, String identityCard) {
        List<UserDocEntity> list =userDocDao.queryUserDocBackground(name,identityCard);
        UserDocEntity userDocEntity=new UserDocEntity();
        boolean isFirstLeave=true;
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        for (int i=0;i<list.size();i++){
            int sumCommunication=0,sumWorkingAttitude=0,sumWorkingAbility=0,sumPunishment=0;
            int entryYear,entryMonth,leaveYear,leaveMonth,month=0,year=0;
            int loyal=100,count,lifeAttitude=100;
            int workEarly=0,workLate=0,absenteeismDays=0;
           userDocEntity =list.get(i);
            //处分记录
           ArrayList<PunishmentEntity> punishmentEntities= (ArrayList<PunishmentEntity>) punishmentService.getList(userDocEntity.getCompanyId(),userDocEntity.getUserId());
           userDocEntity.setPunishment(punishmentEntities);
           ArrayList<UserDocEvaluateEntity> userDocEvaluateEntities= (ArrayList<UserDocEvaluateEntity>) userDocEvaluateService.getList(userDocEntity.getCompanyId(),userDocEntity.getUserId());
           ArrayList<WorkRecordEntity> workRecordEntities= (ArrayList<WorkRecordEntity>) workRecordService.getListByUserId(userDocEntity.getCompanyId(),userDocEntity.getUserId());
           for (int z=0;z<workRecordEntities.size();z++){
               WorkRecordEntity workRecordEntity=workRecordEntities.get(z);
                workEarly=workRecordEntity.getWorkEarly();
                workLate=workRecordEntity.getWorkLate();
                absenteeismDays=workRecordEntity.getAbsenteeismDays();
                lifeAttitude=lifeAttitude-workEarly-workLate-3*absenteeismDays;
           }
           for (int y=0;y<punishmentEntities.size();y++){

               PunishmentEntity punishmentEntity=punishmentEntities.get(y);
               if (punishmentEntity.getPunishmentLeve().equals("记过")){
                   sumPunishment+=5;
               }else if (punishmentEntity.getPunishmentLeve().equals("警告")){
                   sumPunishment+=10;
               }else if(punishmentEntity.getPunishmentLeve().equals("严重警告")){
                    sumPunishment+=15;
               }else if(punishmentEntity.getPunishmentLeve().equals("开除")){
                   sumPunishment+=20;
               }
           }
           //评价总数
           count=userDocEvaluateEntities.size();
           for (int x=0;x<count;x++){
                UserDocEvaluateEntity userDocEvaluateEntity=userDocEvaluateEntities.get(x);
                sumCommunication+=userDocEvaluateEntity.getCommunication();
                sumWorkingAbility+=userDocEvaluateEntity.getWorkingAbility();
                sumWorkingAttitude+=userDocEvaluateEntity.getWorkingAttitude();
            }
           if (count==0){
               count=1;sumCommunication=100;sumWorkingAbility=100;sumWorkingAttitude=100;
           }
           userDocEntity.setEvaluate(userDocEvaluateEntities);
           userDocEntity.setCommunication(sumCommunication/count);
           userDocEntity.setWorkingAbility(sumWorkingAbility/count-sumPunishment);
           userDocEntity.setWorkingAttitude(sumWorkingAttitude/count);
           if (userDocEntity.getStatus()==2) {
               try {
                   //将入职日期string转换为date
                   Date entryDate = df.parse(userDocEntity.getEntryDate());
                   //将离职日期string转换为date
                   Date leaveDate = df.parse(userDocEntity.getLeaveDate());
                   //将入日期date转换为Calendar
                   Calendar entryCal = Calendar.getInstance();
                   entryCal.setTime(entryDate);
                   //将离职日期date转换为Calendar
                   Calendar leaveCal = Calendar.getInstance();
                   leaveCal.setTime(leaveDate);
                   //获取入职日期年月
                   entryYear = entryCal.get(Calendar.YEAR);
                   entryMonth = entryCal.get(Calendar.MONTH);
                   //获取离职日期年月日
                   leaveYear = leaveCal.get(Calendar.YEAR);
                   leaveMonth = leaveCal.get(Calendar.MONTH);
                   if (leaveYear - entryYear > 3 && leaveMonth < entryMonth) {
                       year = leaveYear - entryYear - 1;
                       month = leaveMonth - entryMonth + 12;
                       if (isFirstLeave = false)
                           isFirstLeave = true;
                       loyal += 0;
                   } else if (leaveYear - entryYear >= 2 && leaveMonth >= entryMonth) {
                       year = leaveYear - entryYear;
                       month = leaveMonth - entryMonth;
                       if (isFirstLeave = false)
                           isFirstLeave = true;
                       loyal += 0;
                   } else if ((leaveYear - entryYear >= 2 && leaveMonth < entryMonth)) {
                       year = leaveYear - entryYear - 1;
                       month = leaveMonth - entryMonth + 12;
                       //判断是不是第一次离职
                       if (isFirstLeave) {
                           loyal -= 5;
                           isFirstLeave = false;
                       } else {
                           loyal -= 10;
                       }
                   } else if (leaveYear - entryYear >= 1 && leaveMonth >= entryMonth) {
                       year = leaveYear - entryYear;
                       month = leaveMonth - entryMonth;
                       //判断是不是第一次离职
                       if (isFirstLeave) {
                           loyal -= 5;
                           isFirstLeave = false;
                       } else {
                           loyal -= 10;
                       }
                   } else {
                       if (isFirstLeave) {
                           loyal -= 10;
                           isFirstLeave = false;
                       } else {
                           loyal -= 20;
                       }
                       year = leaveYear - entryYear;
                       month = leaveMonth - entryMonth;
                   }
               } catch (ParseException e) {
                   e.printStackTrace();
               }
           }else if (userDocEntity.getStatus()==1) {
               try { //将入职日期string转换为date
                   Date entryDate = df.parse(userDocEntity.getEntryDate());
                   Calendar entryCal = Calendar.getInstance();
                   entryCal.setTime(entryDate);
                   //获取入职日期年月
                   entryYear = entryCal.get(Calendar.YEAR);
                   entryMonth = entryCal.get(Calendar.MONTH);
                   //获取当前时间/年月
                   Calendar calendar = Calendar.getInstance();
                   int newYear=calendar.get(Calendar.YEAR);
                   int newMonth=calendar.get(Calendar.MONTH);
                    if (newMonth<entryMonth){
                        month=newMonth-entryMonth+12;
                        year=newYear-entryYear-1;
                    }else {
                        year = newYear - entryYear;
                        month = newMonth - entryMonth;
                    }

               } catch (ParseException e) {
                e.printStackTrace();
            }

        }
            userDocEntity.setLoyal(loyal);
            userDocEntity.setYear(year);
            userDocEntity.setMonth(month);
            userDocEntity.setLifeAttitude(lifeAttitude);
            //替换旧值,赋值新值
            list.set(i,userDocEntity);
            System.out.println(userDocEntity.getLifeAttitude()+"1");
            System.out.println(userDocEntity.getLoyal()+"2");
            System.out.println(userDocEntity.getWorkingAbility()+"3");
            System.out.println(userDocEntity.getWorkingAttitude()+"4");
            System.out.println(userDocEntity.getCommunication()+"5");
            System.out.println(userDocEntity.toString());

    }
        return list;
    }

    @Override
    public CountEntity getCount(Long companyId) {
        CountEntity countEntity=userDocDao.getCount(companyId);
        return countEntity;
    }
}


